package com.qf.fmall2204.filter;

import cn.hutool.jwt.JWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Component("jwt")
@Slf4j
public class TokenFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        HttpServletRequest req = (HttpServletRequest) request;

        if (req.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            return true;
        }

        String token = req.getHeader("token");
        if (token != null) {

            boolean validate = JWT.of(token).setKey("qfsyjava2204".getBytes())
                    .validate(0);
            if (validate){
                JWT jwt = JWT.of(token);
                String userjson = (String) jwt.getPayload("sub");
                String perms = (String) jwt.getPayload("perms");

                Subject subject = SecurityUtils.getSubject();
                subject.login(new JwtToken(userjson,perms));

                log.debug("{}携带了token有效，放行",req.getRequestURL());
                return true;
            }else {
                log.debug("token 无效");
                return false;
            }

        } else {
            log.debug("{}没有携带token，拒绝访问",req.getRequestURL());
            return false;
        }

    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }
}
